<?php
/**
 * 字符串操作帮助方法类
 */
class Helper_String
{
    /**
     * 将字符串分割成数组
     *
     * @param string 待分割的字符串
     * @param string 分割符
     * @param mixed $trim 分割后的元素回调处理函数
     *   - true - 对元素运用trim函数
     *   - string - 对元素运用trim函数，将string传为第二个参数
     *   - callable - 任意回调函数
     * @param boolean 是否去除空字符串
     * @return array
     */
    public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
    {
        $result = explode($delimiter, $string);
        if ($trim) {
            if ($trim === true) {
                $trim = 'trim';
            } elseif (!is_callable($trim)) {
                $trim = function ($v) use ($trim) {
                    return trim($v, $trim);
                };
            }
            $result = array_map($trim, $result);
        }
        if ($skipEmpty) {
            // Wrapped with array_values to make array keys sequential after empty values removing
            $result = array_values(array_filter($result, function ($value) {
                return $value !== '';
            }));
        }
        return $result;
    }

    /**
     * 组合条件
     * @return str;
     */
    public static function joinArr($data, $pk = 'id'){

        $str = '';
        $where = '';
        foreach($data as $key => $v){
            if($key == $pk){
                $where = ' WHERE ' . $pk . ' = ' . $v;
                continue;
            }
            if(!is_numeric($v)){
                $v = '"' . $v . '"';
            }
            $str .= $key . ' = ' . $v . ', ';
        }
        return rtrim($str, ', ') . $where;
    }
}